package com.example.eback.controller;
import com.example.eback.dao.FilesDAO;
import com.example.eback.entity.UpLoadFile;
import com.example.eback.entity.User;
import com.example.eback.result.ProcessResponse;
import com.example.eback.result.Result;
import com.example.eback.result.ResultCode;
import com.example.eback.result.ResultFactory;
import com.example.eback.service.FilePathToUrlService;
import com.example.eback.service.FileProcessService;
import com.example.eback.service.FileService;
import com.example.eback.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {
    @Value("${base_up}")
    String base_up;

    @Autowired
    private FileService fileService;

    @Autowired
    private FilePathToUrlService filePathToUrlService;
    @Autowired
    private UserUtils userUtils;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FileProcessService fileProcessService;
    @Autowired
    private FilesDAO filesDAO;

    /**
     * 上传原始文件
     * @param file
     * @param id
     * @return
     */
    @PostMapping("/upload")
    public Result handleFileUpload(MultipartFile file, @RequestParam("historyid") int id/*,@RequestParam("projId") int projId*/) {
        try {
            // 文件上传逻辑
            if (file.isEmpty()) {
                return ResultFactory.buildFailResult("文件为空");
            }
            // 创建文件存储目录，如果不存在
            Path storageDirectory = Paths.get(base_up+"UploadOriginFile/");
            if (!java.nio.file.Files.exists(storageDirectory)) {
                java.nio.file.Files.createDirectories(storageDirectory);
            }
            // 保存文件到文件存储目录
            String oringin_name=file.getOriginalFilename();
            String new_name= fileService.renameFile(file.getOriginalFilename());
            Path filePath = storageDirectory.resolve(new_name);
            Files.copy(file.getInputStream(), filePath);
            //获取用户
            User current_User=userUtils.getCurrentUser();

            // 获取服务器的基础URL
            String uploadfileUrl=filePathToUrlService.convert("UploadOriginFile/"+new_name);

            //创建UpLoadFile对象，将其保存到数据库中
            UpLoadFile currentUpLoadFile =filesDAO.findByUserIdAndId(current_User.getId(),id);
            currentUpLoadFile.setFileName(new_name);
            currentUpLoadFile.setOrigin_filename(oringin_name);
            currentUpLoadFile.setFileUrl(uploadfileUrl);
            currentUpLoadFile.setStatus(1);
            //currentUpLoadFile.setPid(projId);
            fileService.saveFile(currentUpLoadFile);
            return ResultFactory.buildResult(ResultCode.SUCCESS,"文件上传成功",uploadfileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultFactory.buildFailResult(e.getMessage());
        }
    }

    /**
     * 上传标签文件
     * @param file
     * @param id
     * @return
     */
    @PostMapping("/uploadlabel")
    public Result handleLabelFileUpload(MultipartFile file, @RequestParam("historyid") int id) {
        try {
            // 文件上传逻辑
            if (file.isEmpty()) {
                return ResultFactory.buildFailResult("文件为空");
            }
            // 创建文件存储目录，如果不存在
            Path storageDirectory = Paths.get(base_up+"UploadLabelFile/");
            if (!java.nio.file.Files.exists(storageDirectory)) {
                java.nio.file.Files.createDirectories(storageDirectory);
            }
            // 保存文件到文件存储目录
            String oringin_name=file.getOriginalFilename();
            String new_name= fileService.renameFile(oringin_name);
            Path filePath = storageDirectory.resolve(new_name);
            Files.copy(file.getInputStream(), filePath);

            // 获取服务器的基础URL
            String uploadlabelfileUrl=filePathToUrlService.convert("UploadLabelFile/"+new_name);

            //创建UpLoadFile对象，将其保存到数据库中
            User current_User=userUtils.getCurrentUser();
            UpLoadFile currentUpLoadFile =filesDAO.findByUserIdAndId(current_User.getId(),id);
            currentUpLoadFile.setLabelUrl(uploadlabelfileUrl);
            fileService.saveFile(currentUpLoadFile);
            HashMap<String, String> fileUrls = new HashMap<>();
            // 添加键值对
            fileUrls.put("LabelFileUrl",uploadlabelfileUrl);
            fileUrls.put("labelnum",fileProcessService.LabelNumProcess(uploadlabelfileUrl));
            return ResultFactory.buildResult(ResultCode.SUCCESS,"文件上传成功",fileUrls);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultFactory.buildFailResult(e.getMessage());
        }
    }

    /**
     * 上传历史记录的封面快照
     * @param file
     * @param id
     * @return
     */
    //上传历史记录的快照文件
    @PostMapping("/uploadavatar")
    public Result UploadFileAvatar(MultipartFile file, @RequestParam("historyid") int id) {
        try {
            // 文件上传逻辑
            if (file.isEmpty()) {
                return ResultFactory.buildFailResult("文件为空");
            }
            // 创建文件存储目录，如果不存在
            Path storageDirectory = Paths.get(base_up+"FileAvatar/");
            if (!java.nio.file.Files.exists(storageDirectory)) {
                java.nio.file.Files.createDirectories(storageDirectory);
            }
            // 保存文件到文件存储目录
            String oringin_name=file.getOriginalFilename();
            String new_name= fileService.renameFile(oringin_name);
            Path filePath = storageDirectory.resolve(new_name);
            Files.copy(file.getInputStream(), filePath);

            // 获取服务器的基础URL
            String avatarFileUrl=filePathToUrlService.convert("FileAvatar/"+new_name);

            //创建UpLoadFile对象，将其保存到数据库中
            User current_User=userUtils.getCurrentUser();
            UpLoadFile currentUpLoadFile =filesDAO.findByUserIdAndId(current_User.getId(),id);
            currentUpLoadFile.setAvatarFileUrl(avatarFileUrl);
            fileService.saveFile(currentUpLoadFile);
            return ResultFactory.buildResult(ResultCode.SUCCESS,"文件上传成功",avatarFileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultFactory.buildFailResult(e.getMessage());
        }
    }

    @PostMapping("/seg")
    public Result handleFileSeg(@RequestBody Map<String,Object> json) {
        try {
            //传入flask后端进行3D分割，返回一个response对象，里面包含了两个fileURL
            int modelName=(int)json.get("modelname");
            int historyid=(int)json.get("historyid");

            User current_User=userUtils.getCurrentUser();
            int current_userID=current_User.getId();

            UpLoadFile upLoadFile=filesDAO.findByUserIdAndId(current_userID,historyid);
            //分割
            ProcessResponse response=fileProcessService.FileProcess(upLoadFile.getFileUrl());
            //创建UpLoadFile对象，将其保存到数据库中

            upLoadFile.setVnetoriginfileUrl(response.getOriginFileUrl());
            upLoadFile.setLabelUrl(response.getPredictFileUrl());
            upLoadFile.setStatus(2);
            upLoadFile.setModelName(modelName);
            fileService.saveFile(upLoadFile);

            HashMap<String, String> fileUrls = new HashMap<>();
            // 添加键值对
            fileUrls.put("OriginFileUrl",response.getOriginFileUrl());
            fileUrls.put("PredictFileUrl", response.getPredictFileUrl());
            fileUrls.put("labelnum",response.getLabelnum());

            return ResultFactory.buildResult(ResultCode.SUCCESS,"文件处理成功",fileUrls);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultFactory.buildFailResult(e.getMessage());
        }
    }



}

